/*
   Copyright (c) 2023 李伟国
   learner-platform is licensed under Mulan PSL v2.
   You can use this software according to the terms and conditions of the Mulan PSL v2.
   You may obtain a copy of Mulan PSL v2 at:
               http://license.coscl.org.cn/MulanPSL2
   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.  
   See the Mulan PSL v2 for more details. 
*/

package cn.platform.controller;

import cn.platform.config.properties.ConfigShiroProperties;
import cn.platform.constant.RedisConstant;
import cn.platform.dto.ChangePasswordDto;
import cn.platform.dto.LoginDto;
import cn.platform.entity.Role;
import cn.platform.entity.User;
import cn.platform.response.ResponseData;
import cn.platform.response.SuccessResponseData;
import cn.platform.service.ILoginService;
import cn.platform.service.IRoleService;
import cn.platform.service.IUserRoleService;
import cn.platform.utils.RedisUtil;
import com.google.code.kaptcha.Producer;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Collections;
import java.util.UUID;

@Controller
public class LoginController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private ILoginService loginService;

    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private RedisUtil redisUtil;

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseData login(@RequestBody LoginDto loginDto, HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            System.out.println(cookie.getName());
            if(cookie.getName().equals("kaptchaOwner")){
                System.out.println(cookie.getValue());
                loginDto.setKaptchaOwner(cookie.getValue());
            }
        }
        String login = loginService.login(loginDto,request);
        log.info(login);
        return new SuccessResponseData(login);
    }

    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResponseData register(@RequestBody User user){
        loginService.register(user);
        return SUCCESS_INFO;
    }

    @RequestMapping(value = "/active/{activeCode}", method = RequestMethod.GET)
    public String active(@PathVariable("activeCode") String activeCode){
        loginService.active(activeCode);
        return "/active-success.html";
    }

    @ResponseBody
    @RequestMapping(value = "/verification", method = {RequestMethod.GET})
    public ResponseData getKaptcha(HttpServletResponse response/*, HttpSession session*/){
        //生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);

        //验证码的归属
        String kaptchaOwner = UUID.randomUUID().toString().substring(0,10);
        String redisKey = RedisConstant.LOGIN_VERIFICATION.getValue()+kaptchaOwner;

        response.setHeader("kaptcha", kaptchaOwner);
        //将验证码存入redis
        redisUtil.set(redisKey, text, 60);
        // 将验证码图片转成base64
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image,"png",os);
        } catch (IOException e) {
            log.error("响应验证码失败"+e.getMessage());
        }
        return new SuccessResponseData(Base64.getEncoder().encodeToString(os.toByteArray()));

    }

    @ResponseBody
    @RequestMapping(value = "/logout")
    public ResponseData logout(HttpServletRequest request){
        loginService.logout(request);
        return SUCCESS_INFO;
    }

    @ResponseBody
    @RequestMapping(value = "/send/code")
    public ResponseData sendCheckCode(@RequestParam(value = "username", required = false) String username){
        String s = loginService.sendCheckCode(username);
        return new SuccessResponseData(s);
    }

    @ResponseBody
    @RequestMapping(value = "/reset/password")
    public ResponseData changePassword(@RequestBody ChangePasswordDto changePasswordDto){
        loginService.changePassword(changePasswordDto);
        return SUCCESS_INFO;
    }

    @ResponseBody
    @RequestMapping(value = "/un/login", method = RequestMethod.GET)
    public ResponseData unLogin(HttpServletResponse httpServletResponse){
        throw new UnauthenticatedException();   // 未登录
    }

    @ResponseBody
    @RequestMapping("/un/authorized")
    public ResponseData unAuthorized(HttpServletRequest request, HttpServletResponse response){
        throw new UnauthorizedException();  // 无权限
    }

}
